package com.xiaoming.plugin.tcp.utils;

import com.alibaba.fastjson.JSONObject;

public class Res {

    public Res(int code, String method, String message, Object data) {
        this.method = method;
        this.message = message;
        this.code = code;
        this.data = data;
    }

    private JSONObject toJSONObject() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code", this.code);
            jsonObject.put("method", this.method);
            jsonObject.put("message", this.message);
            jsonObject.put("data", this.data);
        } catch (Exception e) {
            jsonObject.put("data", e.getMessage());
        } finally {
            return jsonObject;
        }
    }

    public static JSONObject returnSuccess(String method, Object data) {
        if (data == null) data = true;
        Res res = new Res(200, method, null, data);
        return res.toJSONObject();
    }

    public static JSONObject returnError(String method, String message) {
        Res res = new Res(400, method, message, null);
        return res.toJSONObject();
    }

    public static JSONObject returnError(String method, Throwable exception) {
        Res res = new Res(400, method, getExceptionMessage(exception), null);
        return res.toJSONObject();
    }

//    public static Res sendSuccess(String method, String message, Object data) {
//        Res res = new Res(0, method, message, data);
//        return res;
//    }

    public static JSONObject sendSuccess(String method, Object data) {
        Res res = new Res(0, method, null, data);
        return res.toJSONObject();
    }

    public static JSONObject sendError(String method, String message) {
        Res res = new Res(-1, method, message, null);
        return res.toJSONObject();
    }

    public static JSONObject sendError(String method, Throwable exception) {
        Res res = new Res(-1, method, getExceptionMessage(exception), null);
        return res.toJSONObject();
    }

    private static String getExceptionMessage(Throwable exception) {
        String exStr = exception.getMessage();
        if (exStr == null || exStr == "")
            exStr = exception.toString();
        return exStr;
    }

    private int code;//400操作失败 200操作成功 0主动发送的消息 -1主动发送的异常消息
    private Object data;
    private String method;
    private String message;
}
